import * as vscode from 'vscode';
import {
  Task,
  TaskGroup,
  TaskStatus,
  TaskTag,
  getStatusColor,
  getTagColor,
  getStatusText,
  getTagText,
} from '../models/todo';
import { TodoStateService } from '../services/todo-state.service';

import { BaseTreeItem } from '../models/base-tree-item';

class TodoItem extends BaseTreeItem {
  constructor(
    public readonly task: Task | TaskGroup,
    public readonly type: 'task' | 'group',
    public readonly collapsibleState: vscode.TreeItemCollapsibleState
  ) {
    super(
      type === 'task' ? (task as Task).title : (task as TaskGroup).name,
      collapsibleState
    );
    
    this.setContextValue(type);
    this.configureAppearance();
  }

  private configureAppearance(): void {
    if (this.type === 'task') {
      this.configureTaskAppearance(this.task as Task);
    } else {
      this.setIcon(new vscode.ThemeIcon('folder'));
    }
  }

  private configureTaskAppearance(taskItem: Task): void {
    // 设置图标和状态颜色
    this.setIcon(new vscode.ThemeIcon(
      'circle-outline',
      new vscode.ThemeColor(getStatusColor(taskItem.status))
    ));
    
    // 设置描述和提示信息
    const statusText = getStatusText(taskItem.status);
    const tagText = taskItem.tag ? getTagText(taskItem.tag) : '';
    
    this.setDescription(tagText ? `${statusText} | ${tagText}` : statusText);
    this.setTooltip(tagText
      ? `状态: ${statusText}\n标签: ${tagText}`
      : `状态: ${statusText}`);
    
    // 设置标签颜色
    if (taskItem.tag) {
      this.setHighlight(getTagColor(taskItem.tag));
    }
  }
}

export class TodoProvider implements vscode.TreeDataProvider<TodoItem> {
  private _onDidChangeTreeData: vscode.EventEmitter<
    TodoItem | undefined | null | void
  > = new vscode.EventEmitter<TodoItem | undefined | null | void>();
  readonly onDidChangeTreeData: vscode.Event<
    TodoItem | undefined | null | void
  > = this._onDidChangeTreeData.event;

  private stateService: TodoStateService;

  constructor(private context: vscode.ExtensionContext) {
    this.stateService = new TodoStateService(context);
  }

  refresh(): void {
    this._onDidChangeTreeData.fire();
  }

  getTreeItem(element: TodoItem): vscode.TreeItem {
    return element;
  }

  getChildren(element?: TodoItem): Thenable<TodoItem[]> {
    if (!element) {
      const items: TodoItem[] = [];
      const groups = this.stateService.getGroups();
      const tasks = this.stateService.getTasks();

      // Add groups
      groups
        .sort((a, b) => a.order - b.order)
        .forEach((group) => {
          items.push(
            new TodoItem(
              group,
              'group',
              vscode.TreeItemCollapsibleState.Expanded
            )
          );
        });

      // Add ungrouped tasks
      tasks
        .filter((task) => !task.groupId)
        .sort((a, b) => a.order - b.order)
        .forEach((task) => {
          items.push(
            new TodoItem(task, 'task', vscode.TreeItemCollapsibleState.None)
          );
        });

      return Promise.resolve(items);
    }

    if (element.type === 'group') {
      const group = element.task as TaskGroup;
      const tasks = this.stateService.getTasks();
      return Promise.resolve(
        tasks
          .filter((task) => task.groupId === group.id)
          .sort((a, b) => a.order - b.order)
          .map(
            (task) =>
              new TodoItem(task, 'task', vscode.TreeItemCollapsibleState.None)
          )
      );
    }

    return Promise.resolve([]);
  }

  // 移除了状态管理相关方法，现在由TodoStateService处理

  // Task management - 现在委托给TodoStateService处理
  async createTask(title: string, groupId?: string) {
    await this.stateService.createTask(title, groupId);
    this.refresh();
  }

  async createGroup(name: string) {
    await this.stateService.createGroup(name);
    this.refresh();
  }

  async deleteTask(taskId: string) {
    await this.stateService.deleteTask(taskId);
    this.refresh();
  }

  async deleteGroup(groupId: string) {
    await this.stateService.deleteGroup(groupId);
    this.refresh();
  }

  async updateTaskStatus(taskId: string, status: TaskStatus) {
    await this.stateService.updateTaskStatus(taskId, status);
    this.refresh();
  }

  async updateTaskTag(taskId: string, tag: TaskTag) {
    await this.stateService.updateTaskTag(taskId, tag);
    this.refresh();
  }

  async moveTask(taskId: string, targetGroupId: string | null) {
    await this.stateService.moveTask(taskId, targetGroupId);
    this.refresh();
  }

  async reorderTask(taskId: string, targetTaskId: string | null) {
    await this.stateService.reorderTask(taskId, targetTaskId);
    this.refresh();
  }

  async reorderGroup(groupId: string, targetGroupId: string | null) {
    await this.stateService.reorderGroup(groupId, targetGroupId);
    this.refresh();
  }

  getTasksStats() {
    return this.stateService.getTasksStats();
  }

  async updateGroupName(groupId: string, newName: string) {
    await this.stateService.updateGroupName(groupId, newName);
    this.refresh();
  }

  getGroups() {
    return this.stateService.getGroups();
  }
}
